package com.xianyun.site.support;

import com.alibaba.cloud.spring.boot.sms.ISmsService;
import com.alibaba.cola.catchlog.CatchAndLog;
import com.alibaba.cola.dto.Response;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsResponse;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.xianyun.site.support.api.SmsServiceI;
import com.xianyun.site.support.dto.ReceiveCmd;
import com.xianyun.site.support.dto.SmsReceiveCmd;
import com.xianyun.site.support.dto.clientobject.CheckParamCO;
import com.xianyun.site.support.executor.commond.SmsReceiveCmdExo;
import com.xianyun.site.support.executor.handle.sms.v20201114.config.SmsSendStrategyType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author mac_zyj
 */
@Slf4j
@Service
@CatchAndLog
public class SmsServiceImpl implements SmsServiceI {

    @Autowired
    private ISmsService smsService;

    @Autowired
    private SmsReceiveCmdExo smsReceiveCmdExo;

    @Override
    public Response analyseJsonAndSend(ReceiveCmd receiveCmd, JSONObject receiveObject) {
        CheckParamCO checkParam = receiveCmd.getCheckParam();
        SmsReceiveCmd smsReceiveCmd = receiveObject.toJavaObject(SmsReceiveCmd.class);
        smsReceiveCmd.setCheckParam(receiveCmd.getCheckParam());
        smsReceiveCmd.getSmsMessage().setConditionName(getConditionName(checkParam));
        sendSmsMessage(smsReceiveCmd);
        return Response.buildSuccess();
    }

    @Override
    public SendSmsResponse sendSmsMessage(SmsReceiveCmd smsReceiveCmd) {
        return smsReceiveCmdExo.execute(smsReceiveCmd);
    }


    @Override
    public QuerySendDetailsResponse querySendDetailsByPhoneAndData(String tellPhone, String sendData) {
        // 组装请求对象
        QuerySendDetailsRequest request = new QuerySendDetailsRequest();
        if (null!=tellPhone&&null!=sendData){
            // 必填-号码
            request.setPhoneNumber(tellPhone);
            // 必填-短信发送的日期 支持30天内记录查询（可查其中一天的发送数据），格式yyyyMMdd
            request.setSendDate(sendData);
            // 必填-页大小
            request.setPageSize(10L);
            // 必填-当前页码从1开始计数
            request.setCurrentPage(1L);
            try {
                return smsService.querySendDetails(request);
            }
            catch (ClientException e) {
                e.printStackTrace();
            }
        }
        return new QuerySendDetailsResponse();
    }

    private String getConditionName(CheckParamCO checkParam){
        return checkParam.getModelFunction()+ SmsSendStrategyType.getSmsTypeNameByType(checkParam.getUserAction());
    }

}
